package com.example.defaultshop;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.util.DisplayMetrics;
import android.util.Xml;

public class Server {
	public static final String HOME = "http://defaultshop.bernobox.dk/";
	public static final String MIX = "http://defaultshop.bernobox.dk/XMLgetMix.asp";
	public static final String ADD = "http://defaultshop.bernobox.dk/XMLputbasket.asp";
	public static final String INFO = "http://m.cafecille.dk/info/?shopid=";
	public static final String MENU = "http://defaultshop.bernobox.dk/XMLgetMenu.asp";
	public static final String COPY = "http://defaultshop.bernobox.dk/XMLcopyOrder.asp";
	public static final String CARDS = "http://defaultshop.bernobox.dk/XMLgetCards.asp";
	public static final String SHOP = "http://defaultshop.bernobox.dk/XMLgetShop.asp";
	public static final String ORDER = "http://defaultshop.bernobox.dk/XMLsaveOrder.asp";
	public static final String ORDERS = "http://defaultshop.bernobox.dk/XMLgetOrders.asp";
	public static final String STATUS = "http://defaultshop.bernobox.dk/XMLgetOrderStatus.asp";
	public static final String BASKET = "http://defaultshop.bernobox.dk/XMLgetBasket.asp";
	public static final String STAMPS = "http://defaultshop.bernobox.dk/XMLgetStamps.asp";
	public static final String DELETE = "http://defaultshop.bernobox.dk/XMLdeleteItem.asp";
	public static final String BASKETID = "http://defaultshop.bernobox.dk/XMLgetBasketId.asp";
	public static final String CAMPAIGN = "http://defaultshop.bernobox.dk/XMLgetCampaign.asp";
	public static final String CATEGORIES = "http://defaultshop.bernobox.dk/XMLgetCategories.asp";
	public static final String PRODUCT_IMAGES = "http://m.cafecille.dk/products/";
	public static final String CAMPAIGN_IMAGES = "http://m.cafecille.dk/img/";
	
	public static InputStream get(String urlString) throws IOException {
		InputStream in = null;
        int response = -1;

        URL url = new URL(urlString);
        URLConnection conn = url.openConnection();
                  
        if (!(conn instanceof HttpURLConnection)) throw new IOException("Not an HTTP connection");
        try {
            HttpURLConnection httpConn = (HttpURLConnection) conn;
            httpConn.setAllowUserInteraction(false);
            httpConn.setInstanceFollowRedirects(true);
            httpConn.setRequestMethod("GET");
            httpConn.connect();
 
            response = httpConn.getResponseCode();                
            if (response == HttpURLConnection.HTTP_OK) {
                in = httpConn.getInputStream();                                
            }
        } catch (Exception ex) {
            throw new IOException("Error connecting");           
        }
        return in; 
    }
	
	public static InputStream post(String urlString, String xml) throws IOException {
		InputStream in = null;
        int response = -1;

        URL url = new URL(urlString);
        URLConnection conn = url.openConnection();
                  
        if (!(conn instanceof HttpURLConnection)) throw new IOException("Not an HTTP connection");
        try {
            HttpURLConnection httpConn = (HttpURLConnection) conn;
            httpConn.setAllowUserInteraction(false);
            httpConn.setInstanceFollowRedirects(true);
            httpConn.setRequestMethod("POST");
            httpConn.setDoOutput(true);
            
    		DataOutputStream out = new DataOutputStream(httpConn.getOutputStream());
    		out.write(xml.getBytes("UTF-8"));
    		out.flush();
    		out.close();
            
            httpConn.connect();
 
            response = httpConn.getResponseCode();                
            if (response == HttpURLConnection.HTTP_OK) {
                in = httpConn.getInputStream();                                
            }
        } catch (Exception ex) {
            throw new IOException("Error connecting");           
        }
        return in;
    }
	
	public static XmlPullParser toXmlParser(InputStream in) throws XmlPullParserException, NullPointerException, IllegalArgumentException {
		XmlPullParser parser = Xml.newPullParser();
		parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
    	parser.setInput(in, "UTF-8");
		return parser;
	}
	
	public static Bitmap downloadBitmap(InputStream in, Activity activity) throws IOException, NullPointerException, OutOfMemoryError {
        Bitmap bitmap = null;
        bitmap = BitmapFactory.decodeStream(in);
        
        DisplayMetrics metrics = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        float scaleWidth = metrics.scaledDensity;
        float scaleHeight = metrics.scaledDensity;
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
        
        in.close();
        return resizedBitmap;
    }
	
	public static String getAuthenticationShop(int shopId) {
		return "<?xml version='1.0' encoding='UTF-8'?><GetShop><Athentication>{9B9DF5f-6F59-4E88-99D5-F605FAE3C5B5}</Athentication><ShopId>" + shopId + "</ShopId><Android>1</Android><iOS>0</iOS></GetShop>";
	}
	
	public static String getAuthenticationCampaign(int shopId) {
		return "<?xml version='1.0' encoding='UTF-8'?><GetCampaign><Athentication>{9B9DF5f-6F59-4E88-99D5-F605FAE3C5B5}</Athentication><ShopId>" + shopId + "</ShopId></GetCampaign>";
	}
	
	public static String getAuthenticationBasketId(String phone, int shopId) {
		return "<?xml version='1.0' encoding='UTF-8'?><GetBasketId><Athentication>{9B9DF5f-6F59-4E88-99D5-F605FAE3C5B5}</Athentication><ShopId>" + shopId + "</ShopId><Phone>31237696</Phone></GetBasketId>";
	}
	
	public static String getAuthenticationCard(int shopId) {
		return "<?xml version='1.0' encoding='UTF-8'?><GetCards><Athentication>{9B9DF5f-6F59-4E88-99D5-F605FAE3C5B5}</Athentication><KundeId>" + shopId + "</KundeId></GetCards>";
	}
	
	public static String getAuthenticationCategories(int shopId) {
		return "<?xml version='1.0' encoding='UTF-8'?><GetCategories><Athentication>{9B9DF5f-6F59-4E88-99D5-F605FAE3C5B5}</Athentication><ShopId>" + shopId + "</ShopId></GetCategories>";
	}
	
	public static String getAuthenticationMenu(int shopId, int categoryId) {
		return "<?xml version='1.0' encoding='UTF-8'?><GetMenu><Athentication>{9B9DF5f-6F59-4E88-99D5-F605FAE3C5B5}</Athentication><ShopId>" + shopId + "</ShopId><CategoryId>" + categoryId + "</CategoryId></GetMenu>";
	}
	
	public static String getAuthenticationMix(int shopId, int menuId) {
		return "<?xml version='1.0' encoding='UTF-8'?><GetMix><Athentication>{9B9DF5f-6F59-4E88-99D5-F605FAE3C5B5}</Athentication><ShopId>" + shopId + "</ShopId><MenuId>" + menuId + "</MenuId></GetMix>";
	}
	
	public static String getAuthenticationOrders(String phone, int shopId) {
		return "<?xml version='1.0' encoding='UTF-8'?><GetOrders><Athentication>{9B9DF5f-6F59-4E88-99D5-F605FAE3C5B5}</Athentication><ShopId>" + shopId + "</ShopId><Phone>" + phone + "</Phone></GetOrders>";
	}
	
	public static String getAuthenticationStamps(String phone, int idx) {
		return "<?xml version='1.0' encoding='UTF-8'?><GetStamps><Athentication>{9B9DF5f-6F59-4E88-99D5-F605FAE3C5B5}</Athentication><Idx>" + idx + "</Idx><Phone>" + phone + "</Phone></GetStamps>";
	}
	
	public static String getBasketXml(String phone, int shopId, int basketId) {
		return "<?xml version='1.0' encoding='UTF-8'?><GetBasket><Athentication>{9B9DF5f-6F59-4E88-99D5-F605FAE3C5B5}</Athentication><ShopId>" + shopId + "</ShopId><BasketId>" + basketId + "</BasketId><Phone>" + phone + "</Phone></GetBasket>";
	}
	
	public static String getDeleteBasketItemXml(int idx, int shopId, int basketId) {
		return "<?xml version='1.0' encoding='UTF-8'?><DeleteItem><Athentication>{9B9DF5f-6F59-4E88-99D5-F605FAE3C5B5}</Athentication><Idx>" + idx + "</Idx><ShopId>" + shopId + "</ShopId><BasketId>" + basketId + "</BasketId></DeleteItem>";
	}
	
	public static String getOrderXml(String name, String phone, String message, String early, String late, String address, String zipcode, String city, int shopId, int basketId, int student, int deliver) {
		return "<?xml version='1.0' encoding='UTF-8'?><Order><Athentication>{9B9DF5f-6F59-4E88-99D5-F605FAE3C5B5}</Athentication><ShopId>" + shopId + "</ShopId><BasketId>" + basketId + "</BasketId><Name>" + name + "</Name><Phone>" + phone + "</Phone><Message>" + message + "</Message><Early>" + early + "</Early><Late>" + late + "</Late><StudentCard>" + student + "</StudentCard><Address>" + address + "</Address><Zipcode>" + zipcode + "</Zipcode><City>" + city + "</City><Deliver>" + deliver + "</Deliver></Order>";
	}
	
	public static String getOrderStatusXml(int orderIdx, int shopId, int studentCard, String shopName, String address, String city, String zip) {
		return "<?xml version='1.0' encoding='UTF-8'?><GetOrderStatus><Athentication>{9B9DF5f-6F59-4E88-99D5-F605FAE3C5B5}</Athentication><OrderIdx>" + orderIdx + "</OrderIdx><ShopId>" + shopId + "</ShopId><ShopName>" + shopName.replace("&", "&amp;") + "</ShopName><Address>" + address + "</Address><City>" + city + "</City><PostalCode>" + zip + "</PostalCode><StudentCard>" + studentCard + "</StudentCard></GetOrderStatus>";
	}
	
	public static String getCopyOrderXml(int currentBasketId, int basketId, int shopId, boolean delete, String phone, String ids) {
		return "<?xml version='1.0' encoding='UTF-8'?><CopyOrder><Athentication>{9B9DF5f-6F59-4E88-99D5-F605FAE3C5B5}</Athentication><CurrentBasketId>" + currentBasketId + "</CurrentBasketId><BasketId>" + basketId + "</BasketId><ShopId>" + shopId + "</ShopId><Phone>" + phone + "</Phone><Delete>" + delete + "</Delete><Ids>" + ids + "</Ids></CopyOrder>";
	}
	
	public static String getBasketItemXml(int shopId, int basketId, Item item) {
		String xml = "<?xml version='1.0' encoding='UTF-8'?><Basket>";
		xml += "<Athentication>{9B9DF5f-6F59-4E88-99D5-F605FAE3C5B5}</Athentication>";
		xml += "<ShopId>" + shopId + "</ShopId>";
		xml += "<BasketId>" + basketId + "</BasketId>";
		xml += "<Antal>" + item.getAmount() + "</Antal>";
		xml += "<MenuIdx>" + item.getMenuIdx() + "</MenuIdx>";
		xml += "<OverskriftId>" + item.getCategoryId() + "</OverskriftId>";

		for (MixHeader h : item.getHeaders()) {
			xml += "<Header id=\"" + h.getIdx() + "\">";
			for (Mix m : h.getMix()) {
				if (!m.isHeader()) {
					xml += "<Mix id=\"" + m.getIdx() + "\">";
					switch (m.getType()) {
					case 1:
						xml += "<Option id=\"" + m.getChoice().getIdx() + "\"" + " fyld=\"" + m.getChoice().getName().replace("&", "&amp;") + "\"" +  " pris=\"" + m.getChoice().getPrice() + "\"></Option>";
						break;
					case 2:
						for (Option o : m.getChoices())
							xml += "<Option id=\"" + o.getIdx() + "\"" + " fyld=\"" + o.getName().replace("&", "&amp;") + "\"" + " pris=\"" + o.getPrice() + "\"></Option>";
						break;
					case 3:
						for (Option o : m.getChoices())
							xml += "<Option id=\"" + o.getIdx() + "\"" + " fyld=\"" + o.getName().replace("&", "&amp;") + "\"" + " pris=\"" + o.getPrice() + "\"></Option>";
						break;
					case 4:
						xml += "<Option id=\"" + m.getChoice().getIdx() + "\"" + " fyld=\"" + m.getChoice().getName().replace("&", "&amp;") + "\"" +  " pris=\"" + m.getChoice().getPrice() + "\"></Option>";
						break;
					}
					xml += "</Mix>";
				}
			}
			xml += "</Header>";
		}
		
		for (MixGroup g : item.getGroups()) {
			xml += "<Group id=\"" + g.getIdx() + "\">";
			for (Mix m : g.getMix()) {
				if (!m.isHeader()) {
					xml += "<Mix id=\"" + m.getIdx() + "\">";
					switch (m.getType()) {
					case 1:
						xml += "<Option id=\"" + m.getChoice().getIdx() + "\"" + " fyld=\"" + m.getChoice().getName().replace("&", "&amp;") + "\"" +  " pris=\"" + m.getChoice().getPrice() + "\"></Option>";
						break;
					case 2:
						for (Option o : m.getChoices())
							xml += "<Option id=\"" + o.getIdx() + "\"" + " fyld=\"" + o.getName().replace("&", "&amp;") + "\"" + " pris=\"" + o.getPrice() + "\"></Option>";
						break;
					case 3:
						for (Option o : m.getChoices())
							xml += "<Option id=\"" + o.getIdx() + "\"" + " fyld=\"" + o.getName().replace("&", "&amp;") + "\"" + " pris=\"" + o.getPrice() + "\"></Option>";
						break;
					case 4:
						xml += "<Option id=\"" + m.getChoice().getIdx() + "\"" + " fyld=\"" + m.getChoice().getName().replace("&", "&amp;") + "\"" +  " pris=\"" + m.getChoice().getPrice() + "\"></Option>";
						break;
					}
					xml += "</Mix>";
				}
			}
			xml += "</Group>";
		}
		
		for (Mix m : item.getMix()) {
			if (!m.isHeader()) {
				xml += "<Mix id=\"" + m.getIdx() + "\">";
				switch (m.getType()) {
				case 1:
					xml += "<Option id=\"" + m.getChoice().getIdx() + "\"" + " fyld=\"" + m.getChoice().getName().replace("&", "&amp;") + "\"" +  " pris=\"" + m.getChoice().getPrice() + "\"></Option>";
					break;
				case 2:
					for (Option o : m.getChoices())
						xml += "<Option id=\"" + o.getIdx() + "\"" + " fyld=\"" + o.getName().replace("&", "&amp;") + "\"" + " pris=\"" + o.getPrice() + "\"></Option>";
					break;
				case 3:
					for (Option o : m.getChoices())
						xml += "<Option id=\"" + o.getIdx() + "\"" + " fyld=\"" + o.getName().replace("&", "&amp;") + "\"" + " pris=\"" + o.getPrice() + "\"></Option>";
					break;
				case 4:
					xml += "<Option id=\"" + m.getChoice().getIdx() + "\"" + " fyld=\"" + m.getChoice().getName().replace("&", "&amp;") + "\"" +  " pris=\"" + m.getChoice().getPrice() + "\"></Option>";
					break;
				}
				xml += "</Mix>";
			}
		}

		xml += "</Basket>";
		return xml;
	}
}